import turbogears   as tg

import logging
import cherrypy
import sqlobject
import kaizen
from sqlalchemy.exceptions import SQLError
from kaizen.model import Property, session
from turbogears import identity, expose, validate, validators, redirect, error_handler, flash, view
from formencode import validators

log = logging.getLogger("kaizen.subcontrollers.property")

class PropertyController:
    @expose(template="kaizen.templates.viewSettings", content_type='text/html; charset=utf-8')
    @validate(validators={"key" : validators.NotEmpty()})
    @validate(validators={"value" : validators.NotEmpty()})
    @error_handler()
    def create(self, key, value, tg_errors=None, **keywords):
        if tg_errors:
            tg.flash("You must enter key and value")
            return dict(tg_template="kaizen.templates.createProperty")
        try:
          property = Property(key=key, value=value)
          property.flush()      
        except SQLError:
           tg.flash("Property already exists")
           return dict()
        tg.flash("Property added")
        kaizen.controllers.property_provider.update()
        return dict(property=property)


    @expose(template="kaizen.templates.viewSettings",  content_type='text/html; charset=utf-8', )
    @error_handler()
    def save(self, id, value, tg_errors=None, **keywords):
        #if no title given
        if tg_errors:
            tg.flash("You must enter a value.")
            return dict()
        #update
        try:
          property = session.get(Property,(int(id)))
          if len(value) == 0: # set something since column is 'not null'
           property.value = '0'
          else:
            property.value=value
          property.flush()
        except SQLError,x:
           log.error("error: ", x)
           tg.flash("Property already exists")
           return dict()
        tg.flash("Property updated")
        kaizen.controllers.property_provider.update()
        return dict()

    @expose(template="kaizen.templates.viewSettings", content_type='text/html; charset=utf-8')
    @error_handler()
    def delete(self, id, tg_errors=None, **keywords):
        property = session.get(Property,id)
        property.delete()
        property.flush()
        tg.flash("Property deleted")
        kaizen.controllers.property_provider.update()
        return dict()

